package goodmemo.server;

import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.Logger;
@WebListener
public class Config implements ServletContextListener {
    private static final String ATTRIBUTE_NAME="config";
    private static Logger log = Logger.getLogger(Config.class);
    private DataSource dataSource;

    @Override
    public void contextInitialized(ServletContextEvent event){
        ServletContext servletContext = event.getServletContext();

        String databaseName = servletContext.getInitParameter("database.name");
        try {
            dataSource = (DataSource) new InitialContext().lookup(
                            "java:comp/env/jdbc/goodmemo");

        }catch (NamingException e) {
            log.error("Config error: ",e);
            throw new RuntimeException("Config failed: datasource not found",e);
        }

        servletContext.setAttribute(ATTRIBUTE_NAME,this);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event){
    }

    public DataSource getDataSource(){
        return dataSource;
    }

    public static Config getInstance(ServletContext servletContext){
        return (Config) servletContext.getAttribute(ATTRIBUTE_NAME);
    }
}
